import {
  View,
  Modal,
  TextInput,
  Image,
  TouchableOpacity,
  FlatList,
  StyleSheet,
} from 'react-native';
import React, {useEffect, useState} from 'react';
import {remoteData as dbData} from '../utils/testData';
interface SearchModalProps {
  modalVisible: boolean;
  onClickClose: () => void;
}
import Icon from 'react-native-vector-icons/FontAwesome5';
import {SearchListCell, SearchListProps} from './SearchListCell';
import {getHistoryData, storeSearchHistory} from '../utils/storageUtils';
let historyData: {content: string; flag: number}[] = [];

const SearchModal = (props: SearchModalProps) => {
  const {modalVisible, onClickClose} = props;
  const [inputValue, setInputValue] = useState('');
  const [searchHistory, setSearchHistory] = useState<string[]>(['cce', 'qqq']);
  const textInputRef = React.createRef<TextInput>();

  const [remoteData, setDbData] = useState(dbData);
  const [data, setData] = useState<{flag: number; content: string}[]>([]);

  useEffect(() => {
    getHistoryData().then(data => {
      data.map(item => {
        const tmp = {content: item, flag: 1};
        historyData.push(tmp);
      });
      setData(historyData);
    });
    return () => {
      setInputValue('');
      historyData = [];
    };
  }, [modalVisible]);
  const storeHistory = async (text: string) => {
    const index = historyData.findIndex(item => item.content === text);
    if (index < 0) {
      storeSearchHistory(text);
    }
  };
  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={modalVisible}
      onRequestClose={props.onClickClose}>
      <View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.8)'}}>
        <View style={styles.inputContainer}>
          <Icon.Button
            color={'white'}
            size={20}
            name="chevron-left"
            onPress={onClickClose}
            backgroundColor="transparent"
          />

          <TextInput
            ref={textInputRef}
            value={inputValue}
            style={styles.input}
            placeholder="Search"
            placeholderTextColor={'rgba(255,255,255,0.5)'}
            autoFocus={true}
            returnKeyType="search"
            onSubmitEditing={() => {
              setData([]);
              storeHistory(inputValue);
              textInputRef.current?.blur();
            }}
            onChangeText={text => {
              let tmp: SearchListProps[] = [];
              remoteData.map(item => {
                if (item.includes(text) && text !== '') {
                  console.log('text', text);
                  tmp.push({content: item, flag: 0});
                }
              });
              searchHistory.map(item => {
                if (item.includes(text) && text !== '') {
                  tmp.push({content: item, flag: 1});
                }
              });
              setInputValue(text);
              setData(tmp);
            }}
          />

          <TouchableOpacity onPress={() => setInputValue('')}>
            <Image
              source={require('../image/delete.png')}
              style={styles.deleteIcon}
            />
          </TouchableOpacity>
        </View>
        <FlatList
          data={data}
          renderItem={({item}) => (
            <SearchListCell
              {...item}
              onClickCell={content => {
                setInputValue(content);
                setData([]);
                storeHistory(content);
                textInputRef.current?.blur();
              }}
            />
          )}
        />
      </View>
    </Modal>
  );
};
const styles = StyleSheet.create({
  inputContainer: {
    width: '100%',
    height: 60,
    flexDirection: 'row',
    marginTop: 60,
  },
  input: {
    paddingLeft: 10,
    paddingRight: 30,
    flex: 1,
    backgroundColor: 'gray',
    height: 40,
    borderRadius: 10,
    color: 'white',
  },
  deleteIcon: {
    width: 20,
    height: 20,
    resizeMode: 'contain',
    position: 'absolute',
    right: 10,
    top: 10,
    tintColor: 'white',
  },
});
export default SearchModal;
